package com.longge;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-05-05 02:50
 */
public class CombinationSum {

    ArrayList<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<Integer> path = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, 0, target, path);
        return res;
    }

    private void backtrack(int[] candidates, int start, int target, ArrayList<Integer> path) {
        if (target==0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            target-=candidates[i];
            if (target<0) return;
            path.add(candidates[i]);
            backtrack(candidates, i, target, path);
            path.remove(path.size() - 1);
            target+=candidates[i];
        }
    }

    public static void main(String[] args) {
        new CombinationSum().combinationSum(new int[]{2,3,7},7);
    }
}
